import request from '@/util/request.ts'
import type {
  loginFormData,
  loginResponseData
} from './type'
import {useUserStore} from "../../stores/modules/user";

const userStore = useUserStore()
enum API {
  CHAT_URL = import.meta.env.VITE_APP_BASE_API + '/ai/chat',
  CHAT_LIST_URL = '/ai/list',
  CHAT_LIST_DETAIL_URL = '/ai/chatList/',
  CHAT_DEL_URL = '/ai/del/',
}

// 获取历史列表
export const reqChatList = () => {
  return request.get(API.CHAT_LIST_URL)
}


// 删除某个对话
export const reqDelChat = (id) => {
  return request.get(API.CHAT_DEL_URL + `/${id}`)
}

// 获取会话下对话详情
export const reqChatDetail = (id) => {
  return request.get(API.CHAT_LIST_DETAIL_URL + `/${id}`)
}


// 对话
export const reqChatStream = async (data, { onMessage, onError, onComplete }) => {
  try {
    const response = await fetch(API.CHAT_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json",
        token: userStore.token
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);

    // 从响应流中读取数据
    const reader = response.body.getReader();
    const decoder = new TextDecoder();

    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        onComplete?.(); // 流结束
        break;
      }

      // 处理分块数据（假设后端返回的是 NDJSON 或纯文本）
      const chunk = decoder.decode(value, { stream: true });
      try {
        // console.log(`2` , chunk.replace('data:' , ''));
        const parsed = JSON.parse(chunk.replace('data:' , '')); // 如果是 JSON 数据
        onMessage(parsed);
      } catch (e) {
        console.error(e)
        console.warn("Non-JSON chunk:", chunk); // 原始文本处理
      }
    }
  } catch (error) {
    onError?.(error);
  }
};
